package com.ybkj.daijia.server.amqp.rabbitTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.serverUtils.SettingUtils;
import java.io.IOException;
import java.io.Serializable;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

/**
 * @author jacklee
 */
@Component
@Scope("prototype")
public class PushTemplate extends BaseTemplate {

    public static String AMQP_HOST;
    public static String AMQP_PORT;
    public static String AMQP_USERNAME;
    public static String AMQP_PASSWORD;
    public static String AMQP_SP_EXCHANGE;

    static {
        try {
            Properties prop = PropertiesLoaderUtils.loadAllProperties("config.properties");
            AMQP_HOST = prop.getProperty("amqp.host");
            AMQP_PORT = prop.getProperty("amqp.port");
            AMQP_USERNAME = prop.getProperty("amqp.username");
            AMQP_PASSWORD = prop.getProperty("amqp.password");
            AMQP_SP_EXCHANGE = prop.getProperty("amqp.sp.exchange");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private SettingUtils setting;

    /**
     * 构造方法初始化rabbit配置
     *
     * @throws TimeoutException
     * @throws IOException
     */
    public PushTemplate() throws IOException, TimeoutException {
        super(AMQP_HOST, AMQP_PORT, AMQP_USERNAME, AMQP_PASSWORD, AMQP_SP_EXCHANGE);
    }

    /**
     * 发送消息到队列服务器 object 发送的消息对象（需要强转Serializable类型）
     */
    public void sendMessage(Serializable object) {
        try {

            JSONObject jo = (JSONObject) JSON.toJSON(object);
            jo.put("appKey", setting.get().getSecKey());

            channel.basicPublish(AMQP_SP_EXCHANGE, "", null, jo.toString().getBytes("utf-8"));
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}
